package com.drug.mingkang.controller;

import com.drug.mingkang.utils.ErrorCodeEnum;
import com.drug.mingkang.utils.ResponseMessage;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述：自定义异常
 * 所属项目：mingkang
 *
 * @author 依旧
 * @create 2020-08-24 20:34
 * @employ IntelliJ IDEA
 * @since 1.0.0
 */
@Controller
public class ErrorsController implements ErrorController {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseMessage handleError(HttpServletRequest request) {
        //获取statusCode:401,404,500
        // 如果使用ControllerAdvice注解该方法有效
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        System.err.println("statusCode = " + statusCode);

        return new ResponseMessage(statusCode,ErrorCodeEnum.getByCode(statusCode).getDescription(),null);
    }

    @RequestMapping("/error")
    @ResponseBody
    public ResponseMessage errorHtml(HttpServletRequest request) {
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        System.err.println("/error code = " + statusCode+"  "+ErrorCodeEnum.getByCode(statusCode).getDescription());

        return new ResponseMessage(statusCode,ErrorCodeEnum.getByCode(statusCode).getDescription(),null);
    }

    @Override
    public String getErrorPath() {
        return null;
    }
}